import React from 'react'
import { Button,Alert, Checkbox, Col, Form, Icon, Input, message, Modal, Popconfirm, Radio, Row, Table, Tag } from 'antd'
import { fetchPost } from '../../../utils/request'
import Style from './Index.less'
import SearchStyle from '../../common/less/search.less'
import Search from '../../common/components/Search'
import moment from '../outbound'

const FormItem = Form.Item
const CheckboxGroup = Checkbox.Group

class Index extends React.Component {

  constructor (props) {
    super(props)
    this.state = {
      visible: false,
      modalType:1,
      agentList: [],
      page: {
        currentPage: 1,
        pageSize: 100,
        totalCount: 0
      },

      params: {
        stageCode: null
      },

      searchParams: {
        list: [
          {
            name: 'Bucket',
            type: 'select',
            key: 'stageCode',
            className: 'pr20',
            values: [
              { value: '', name: 'Please Select' },
            ],
          },
          {
            name: '',
            type: 'search',
            key: '',
            className: 'pr20',
            values: []
          }
        ],
        api: '/collection/v2/case/query'
      },

      loading: false,
      adminList: [],
      bucketTagList: [],
      userLanguageTagList: [],
      checkedList: [],
      indeterminate: true,
      checkAll: false,
      bucketTagDisabled: false,
    }

  }

  componentDidMount () {
    this.getAgentListData()
    this.getData()
  }

  componentWillReceiveProps (props) {

  }

  //查询角色是催收的人员列表
  getAgentListData () {
    fetchPost('/collection/v2/agent/common/list').then((res) => {
      if (res.code === 0) {
        if (res.data !== null) {
          this.setState({
            adminList: res.data.adminList,
            bucketTagList: res.data.bucketList,
            userLanguageTagList: res.data.userLanguageList,
          })
        }
      } else {
        message.error(res.msg)
      }
    })
  }

  // 获取表格数据
  getData () {
    this.setState({
      loading: true
    })
    const { stageCode } = this.state.params
    fetchPost(`/collection/v2/agent/list/v2?currentPage=${this.state.page.currentPage}&pageSize=${this.state.page.pageSize}`, { stageCode }).then((res) => {
      if (res.code === 0) {
        if (res.data !== null) {
          this.setState({
            agentList: res.data.agentList,
            page: {
              ...this.state.page,
              totalCount: res.page.totalCount || 0
            },
          }, () => {
          })
        }
      } else {
        message.error(res.msg)
      }
    })
    this.setState({
      loading: false
    })
  }

  setPagination () {
    let self = this
    return {
      total: this.state.page.totalCount,
      pageSize: this.state.page.pageSize,
      showSizeChanger: false,
      showQuickJumper: true,
      showTotal (total) {
        return `Total ${total} `
      },
      onChange (current) {
        self.nextPage(current)
      }
    }
  }

  nextPage (currentPage) {
    this.setState({
      page: {
        ...this.state.page,
        currentPage
      }
    }, () => {
      this.getData()
    })
  }

  handleOk = (e) => {
    let self = this
    this.props.form.validateFields((error, values) => {
      console.log(error, values)
      if (!error) {
        let params = {
          adminId: values.adminId,
          account: values.account,
          name: values.name,
          password: values.password,
          bucket: values.bucket,
          userLanguageList: values.userLanguageList,
          maxOrdersNum: values.maxOrdersNum,
          minOrdersNum: values.minOrdersNum
        }
        fetchPost('/collection/v2/agent/save', params).then((res) => {
          if (res.code === 0) {
            message.info(res.msg, 0.2, () => {
              this.setState({
                visible: false,
              }, () => {
                this.getData()
              })
            })
            this.props.form.resetFields()
          } else {
            message.error(res.msg)
          }
        })
      }
    })
  }

  handleCancel = (e) => {
    this.setState({
      visible: false,
    }, () => {

    })
    this.props.form.resetFields()
  }

  forbiddenAdmin (record) {
    fetchPost(`/collection/v2/agent/status/save/v2`, {
      status: 2,
      adminId: record.adminId,
      bucket: record.bucket,
    }).then(res => {
      if (res.code === 0) {
        message.success('Ask for leave successfully.')
        this.getData()
      } else {
        message.error(res.msg)
      }
    })
  }

  recoveryAdmin (record) {
    fetchPost(`/collection/v2/agent/status/save/v2`, {
      status: 1,
      adminId: record.adminId,
      bucket: record.bucket,
    }).then(res => {
      if (res.code === 0) {
        message.success('back to work successfully.')
        this.getData()
      } else {
        message.error(res.msg)
      }
    })
  }

  deleteAdmin (record) {
    fetchPost(`/collection/v2/agent/` + record.adminId + `/delete`, {}).then(res => {
      if (res.code === 0) {
        message.success('Delete successful')
        this.getData()
      } else {
        message.error(res.msg)
      }
    })
  }

  bucketOnChange (checkedList) {
    this.setState({})
  };

  languageOnChange (checkedList) {
    this.setState({})
  }

  showModal = (e,type) => {
    this.setState({
      bucketTagDisabled: false,
      visible: true,
      modalType:type
    })
  }

  edit = record => {
    this.setState({
      bucketTagDisabled: false,
      modalType:2
    })
    this.props.form.setFieldsValue({
      name: record.name,
      adminId: '' + record.adminId,
      account: record.account,
      password: record.password,
      bucket: record.bucket,
      userLanguageList: record.userLanguageList,
      maxOrdersNum: record.maxOrdersNum,
      minOrdersNum: record.minOrdersNum
    })
    this.setState({
      visible: true
    })
  }

  getRowKey (record) {
    return record.adminId + record.bucket
  }

  changeParams (params) {
    this.setState({
      params,
    }, () => {
      this.getData()
    })
  }

  render () {
    const { getFieldDecorator } = this.props.form
    let self = this
    let columns = [
      {
        title: 'Agent Name',
        dataIndex: 'name',
        key: 'name',
      },{
      title: 'Account',
      dataIndex: 'account',
      key: 'account',
    }, {
      title: 'Password',
      dataIndex: 'password',
      key: 'password',
    }, {
      title: 'Bucket',
      dataIndex: 'bucket',
      key: 'bucket',
      render: (text, record) => {
        return (
          <Tag>{record.bucket}</Tag>
        )
      },
    }, {
      title: 'Language',
      dataIndex: 'userLanguageList',
      key: 'userLanguageList',
      render: (text, record) => {
        return record.userLanguageList.map((item) =>
          <Tag>{item}</Tag>
        )
      },
    }, {
      title: 'Max Order Num',
      dataIndex: 'maxOrdersNum',
      key: 'maxOrdersNum',
    }, {
      title: 'Min Order Num',
      dataIndex: 'minOrdersNum',
      key: 'minOrdersNum',
    }, {
      title: 'Edit',
      dataIndex: 'edit',
      render: (text, record) => {
        return (
          <div>
            <a onClick={() => {
              this.edit(record)
            }}
               href='javascript:;'>Edit</a>
          </div>
        )
      },
    }, {
      title: 'Working state',
      // dataIndex: 'status',
      render: (text, record) => {
        const { editable } = record
        return (
          <div>
            {
              record.status == 1 ?
                <Tag color="green">Working</Tag>
                :
                null
            }

            {
              record.status == 2 ?
                <Tag color="orange">On leave</Tag>
                : null
            }
          </div>
        )
      },
    }, {
      title: 'Action',
      dataIndex: 'status',
      render: (text, record) => {
        const { editable } = record
        return (
          <div>
            {
              record.status == 1 ?
                <Popconfirm title='Asked for leave?'
                            onConfirm={() => {
                              this.forbiddenAdmin(record)
                            }}
                            okText='Confirm' cancelText='Cancel'>
                  <a className='operateBtn' href='javascript:;'>Asked for leave</a>
                </Popconfirm>
                :
                null
            }

            {
              record.status == 2 ?
                <Popconfirm title='Back to work?'
                            onConfirm={() => {
                              this.recoveryAdmin(record)
                            }}
                            okText='Confirm' cancelText='Cancel'>
                  <a className='operateBtn' href='javascript:;'>Back to work</a>
                </Popconfirm>
                : null
            }
          </div>
        )
      },
    }, {
      title: 'Delete',
      dataIndex: 'delete',
      render: (text, record) => {
        return (
          <div>
            <Popconfirm title='Confirm to delete this one?'
                        onConfirm={() => {
                          this.deleteAdmin(record)
                        }}
                        okText='Confirm' cancelText='Cancel'>
              <a className='operateBtn' href='javascript:;'>Delete</a>
            </Popconfirm>
          </div>
        )
      },
    }
    ]

    const formItemLayout = {
      labelCol: {
        xs: { span: 8 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 16 },
        sm: { span: 16 },
      },
    }

    return (
      <div>
        <Modal
          title={this.state.modalType===1?"Add Agent":"Edit Agent"}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText="Save"
        >

          <Form style={{ width: '100%', margin: 'auto' }} horizontal>

            <FormItem {...formItemLayout} label="Agent Name">
              {getFieldDecorator('name', {
                rules: [
                  { required: true, message: 'Name is necessary!' },
                ],
              })(
                  <Input disabled={this.state.modalType===2} placeholder="required"/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="adminId" style={{ display: 'none' }}>
              {getFieldDecorator('adminId', {})(
                <Input placeholder="required"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="account">
              {getFieldDecorator('account', {
                rules: [
                  { required: true, message: 'Name is necessary!' },
                ],
              })(
                  <Input disabled={this.state.modalType===2}  placeholder="required"/>
              )}
            </FormItem>


            <FormItem {...formItemLayout} label="password">
              {getFieldDecorator('password', {
                rules: [
                  { required: true, message: 'mobile is necessary!' },
                ],
              })(
                <Input disabled={this.state.modalType===2}  placeholder="required"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Bucket">
              {getFieldDecorator('bucket', {
                initialValue: [],
                rules: [
                  { required: true, message: 'Bucket is necessary!' },
                ],
              })(
                <Radio.Group>
                  {
                    this.state.bucketTagList.map((val, index) => {
                      return (<Radio.Button disabled={this.state.bucketTagDisabled}
                                            value={val}>{val}</Radio.Button>)
                    })
                  }
                </Radio.Group>,
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Language">
              {getFieldDecorator('userLanguageList', {
                initialValue: [],
                rules: [
                  { required: true, message: 'Language is necessary!' },
                ],
              })(
                <Checkbox.Group style={{ width: '100%' }}>
                  <Row>
                    {
                      this.state.userLanguageTagList.map((val, index) => {
                        return (<Col span={8}>
                          <Checkbox value={val}>{val}</Checkbox>
                        </Col>)
                      })
                    }
                  </Row>
                </Checkbox.Group>,
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Max Order Num">
              {getFieldDecorator('maxOrdersNum', {})(
                <Input placeholder="Default unrestricted"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Min Order Num">
              {getFieldDecorator('minOrdersNum', {})(
                <Input placeholder="Default unrestricted"/>
              )}
            </FormItem>

            <Alert message="Attention!!! Agent Name, Account, Password cannot be updated  here once created!! you can ask Admin for help!!" type="warning" />
          </Form>

        </Modal>

        <div className={SearchStyle.searchClass}>
          <Search searchParams={this.state.searchParams} changeParams={(params) => this.changeParams(params)}/>
        </div>

        <div className={Style.title}>
          <Icon className={Style.icon} type='tag-o'/>
          Collection Agent Manage
          <Button className='ml20' onClick={(e) => {
            this.showModal(e,1)
          }} type='primary'> New </Button>
        </div>

        <div>
          <Col span={24}>
            <Table pagination={this.setPagination()}
                   key={(record) => {
                     this.getRowKey(record)
                   }}
                   rowKey={(record) => {
                     this.getRowKey(record)
                   }}
                   bordered
                   dataSource={this.state.agentList}
                   columns={columns}
                   loading={self.state.loading}
                   size='small'
            />
          </Col>
        </div>
      </div>
    )
  }
}

Index = Form.create()(Index)
export default Index
